package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.config.WebSocketServer;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.service.IAlertRuleService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 报警规则Service业务层处理
 *
 * @author alexis
 * @date 2025-03-11
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private IAlertDataService alertDataService;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return alertRuleMapper.deleteById(id);
    }

    @Override
    public void alertFilter() {
        Long count = this.lambdaQuery().eq(AlertRule::getStatus, 1).count();
        if (count <= 0) {
            return;
        }
        List<List<DeviceData>> values = redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        if (CollUtil.isEmpty(values)) {
            return;
        }
        LocalDateTime now = LocalDateTime.now();
        List<DeviceData> deviceDataList = new ArrayList<>();
        values.forEach(deviceDataList::addAll);
        deviceDataList.forEach(deviceData -> alertFilter(deviceData, now));
        log.info("设备数据上报过滤定时任务,执行成功!");
    }

    private void alertFilter(DeviceData deviceData, LocalDateTime now) {
        // 判断当前上报数据是否超过了一分钟
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        if (alarmTime.plusMinutes(1).isBefore(now)) {
            return;
        }
        // 查询所有的该产品规则和该物模型的规则
        List<AlertRule> alertRules = this.lambdaQuery().eq(AlertRule::getIotId, -1)
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId()).list();
        List<AlertRule> iotIdRules = this.lambdaQuery().eq(AlertRule::getIotId, deviceData.getIotId())
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId()).list();
        Collection<AlertRule> allAlertRules = CollUtil.addAll(alertRules, iotIdRules);
        if (CollUtil.isEmpty(allAlertRules)) {
            return;
        }
        allAlertRules.forEach(alertRule -> this.deviceDataFilter(alertRule, deviceData));
    }

    private void deviceDataFilter(AlertRule alertRule, DeviceData deviceData) {
        // 判断生效时间
        String[] times = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime begin = LocalTime.parse(times[0]);
        LocalTime end = LocalTime.parse(times[1]);
        LocalTime alarmTime = deviceData.getAlarmTime().toLocalTime();
        if (alarmTime.isBefore(begin) || alarmTime.isAfter(end)) {
            return;
        }

        // 统计次数的key
        String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + deviceData.getIotId()
                + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        // 判断数据阈值
        // 1大于 -1小于 0等于
        int compare = Double.compare(Double.parseDouble(deviceData.getDataValue()), alertRule.getValue());
        if ((">=".equals(alertRule.getOperator()) && compare < 0) ||
                ("<".equals(alertRule.getOperator()) && compare >= 0)) {
            redisTemplate.delete(aggCountKey);
            return;
        }
        // 判断沉默周期
        String silentKey = CacheConstants.ALERT_SILENT_PREFIX + deviceData.getIotId()
                + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        Object silentData = redisTemplate.opsForValue().get(silentKey);
        if (ObjUtil.isNotNull(silentData)) {
            return;
        }
        // 判断持续周期
        // 统计次数
        Object o = redisTemplate.opsForValue().get(aggCountKey);
        int count = ObjUtil.isNull(o) ? 1 : (int) o + 1;
        if (count < alertRule.getDuration()) {
            redisTemplate.opsForValue().set(aggCountKey, count);
            return;
        }
        // 校验全部通过,当前数据触发报警
        // 删除redis报警数
        redisTemplate.delete(aggCountKey);
        // 添加redis沉迷周期
        redisTemplate.opsForValue().set(silentKey, 1, alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        // 是否是老人数据
        List<Long> empIds;
        if (alertRule.getAlertDataType() == 0) {
            // 是否是随身设备
            if (deviceData.getLocationType() == 0) {
                empIds = deviceMapper.selectNursingIdsByIotIdWithElder(deviceData.getIotId());
            } else {
                empIds = deviceMapper.selectNursingIdsByIotIdWithBed(deviceData.getIotId());
            }
        } else {
            empIds = sysUserRoleMapper.selectUserIdByRoleName("维修工");
        }
        List<Long> adminIds = sysUserRoleMapper.selectUserIdByRoleName("超级管理员");
        Collection<Long> userIds = CollUtil.addAll(empIds, adminIds);
        // 去重
        userIds = CollUtil.distinct(userIds);
        List<AlertData> alertData = this.insertAlertData(alertRule, deviceData, userIds);
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData.get(0), AlertNotifyVo.class);
        alertNotifyVo.setFunctionName(alertRule.getFunctionName());
        alertNotifyVo.setAlertDataType(alertRule.getAlertDataType());
        alertNotifyVo.setVoiceNotifyStatus(0);
        alertNotifyVo.setNotifyType(1);
        alertNotifyVo.setIsAllConsumer(false);
        webSocketServer.sendMessageToConsumer(alertNotifyVo, userIds);
    }

    private List<AlertData> insertAlertData(AlertRule alertRule, DeviceData deviceData, Collection<Long> userIds) {
        AlertData alertData = BeanUtil.toBean(deviceData, AlertData.class);
        alertData.setId(null);
        alertData.setAlertRuleId(alertRule.getId());
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警",
                alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        alertData.setAlertReason(alertReason);
        alertData.setType(alertRule.getAlertDataType());
        alertData.setStatus(0);
        List<AlertData> result = userIds.stream().map(userId -> {
            AlertData newAlertData = BeanUtil.toBean(alertData, AlertData.class);
            newAlertData.setUserId(userId);
            return newAlertData;
        }).collect(Collectors.toList());
        alertDataService.saveBatch(result);
        return result;
    }
}
